import React from "react";

import { Table, Button, Popconfirm, message } from "antd";
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { useEffect, useState } from "react";
import { deleteAdmin } from "@/api/admin";
import {
  getAdminlist,
  // getAdminDetail,
  // addAdmin,
  // deleteAdmin,
  // editAdmin,
} from "@/api/admin";
import { Space } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { changeOpen } from "@/store/modules/admin";
import DrawerEditAdmin from "@/component/drawerEditAdmin";
import { changeEditAdmin } from "../../store/modules/admin";
import ModalAddAdmin from "@/component/modalAddAdmin";
import { Tag } from "antd";

const AdminList = () => {
  //设置state
  //管理列表数据
  const [adminList, setAdminlist] = useState([]);
  //管理列表数据长度
  const [adminListLength, setAdminListLength] = useState([0]);
  //管理当前页码
  const [current, setCurrent] = useState(1);
  //管理页面数据容量
  const [pageSize, setPageSize] = useState(5);
  //管理选中的行
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  //管理抽屉是否打开
  const open = useSelector((state) => state.admin.open);
  //获取登录用户角色
  const adminRole = useSelector((state) => state.admin.role);
  //管理对话框是否打开
  const dispatch = useDispatch();
  const getAdminlistdata = () => {
    getAdminlist().then((res) => {
      setAdminlist(res.data.data);
    });
  };
  //异步ajax获取列表数据
  useEffect(() => {
    getAdminlistdata();
  }, []);

  useEffect(() => {
    if (adminList.length === 0) return;
    setAdminListLength([...adminListLength].concat([adminList.length]));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [adminList.length]);
  //获取数据删除前后的页面差
  const pageArr = adminListLength.slice(-2);
  const getPageChange = (adminListLength) => {
    return Math.ceil(pageArr[0] / pageSize) - Math.ceil(pageArr[1] / pageSize);
  };
  const pagechange = getPageChange(adminListLength);

  //设置表格列
  const columns = [
    {
      title: "序号",
      width: 150,
      render: (text, record, index) => {
        if (pagechange > 0) {
          return (
            <span>
              {(Math.ceil(pageArr[1] / pageSize) - 1) * pageSize + 1 + index}
            </span>
          );
        }
        return <span>{(current - 1) * pageSize + 1 + index}</span>;
      },
    },
    {
      title: "账户",
      dataIndex: "adminname",
      width: 150,
    },
    {
      title: "角色",
      dataIndex: "role",
      render: (text, record, index) => {
        // return <span>{text === 1 ? "管理员" : "超级管理员"}</span>;
        return text === 1 ? (
          <Tag color="#2db7f5">管理员</Tag>
        ) : (
          <Tag color="#87d068">超级管理员</Tag>
        );
      },
    },
    {
      title: "操作",
      render: (text, record, index) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                dispatch(changeOpen(true));
                dispatch(
                  changeEditAdmin({
                    adminname: record.adminname,
                    password: record.password,
                    role: record.role.toString(),
                    checkedKeys: record.checkedKeys,
                  })
                );
              }}
              shape="circle"
              icon={<EditOutlined />}
            />
            <Popconfirm
              title="警告"
              description="确定要删除此行吗？"
              onConfirm={() => {
                deleteAdmin({ adminid: record.adminid }).then((res) => {
                  if (res.data.code === "200") {
                    message.warning("删除成功");
                    getAdminlistdata();
                  } else {
                    message.error("删除失败");
                  }
                });
              }}
              okText="是的"
              cancelText="取消"
            >
              <Button
                type="primary"
                danger
                shape="circle"
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <Table
      columns={columns}
      dataSource={adminList}
      pagination={{
        pageSize,
        showSizeChanger: true,
        defaultCurrent: current,
        pageSizeOptions: [5, 10, 15, 20],
        total: adminList.length,
        // responsive: false,
        showQuickJumper: true,
        showTotal(total, range) {
          return <span>共 {total} 条</span>;
        },
        onChange: (page, pageSize) => {
          console.log("onChange--->", page);
          setCurrent(page);
          setPageSize(pageSize);
        },
      }}
      rowSelection={{
        selectedRowKeys,
        onChange: (newSelectedRowKeys) => {
          setSelectedRowKeys(newSelectedRowKeys);
        },
      }}
      scroll={{
        y: 340,
      }}
      //页头
      title={() => {
        return (
          <Space direction="row">
            {selectedRowKeys.length > 0 ? (
              <Button
                onClick={() => {
                  if (adminRole.toString() !== "2") {
                    message.warning("当前暂无权限");
                    return;
                  }
                  let arr = [];
                  selectedRowKeys.forEach((adminid) => {
                    arr.push(deleteAdmin({ adminid }));
                  });
                  Promise.all(arr).then((res) => {
                    if (res[0].data.code === "200") {
                      message.warning("批量删除成功");
                    } else {
                      message.warning("批量删除失败");
                    }
                    getAdminlistdata();
                  });
                }}
              >
                全部删除
              </Button>
            ) : (
              <Button disabled>全部删除</Button>
            )}
            <ModalAddAdmin update={getAdminlistdata} />
            {open ? <DrawerEditAdmin update={getAdminlistdata} /> : null}
          </Space>
        );
      }}
      //表格行必须有唯一的key
      rowKey={(record) => {
        return record.adminid;
      }}
    />
  );
};
export default AdminList;
// xxx
